#include <iostream>
#include <unordered_set>

using namespace std;

class Trie {
private:
    struct trie_tree {
        bool end = false;
        trie_tree* table[26] {nullptr};
    };
    trie_tree trie_tree_head;
public:
    /** Initialize your data structure here. */
    Trie() {}

    /** Inserts a word into the trie. */
    void insert(string word) {
        trie_tree* trie_node = &trie_tree_head;
        for (char item : word) {
            if (trie_node->table[item - 'a'] == nullptr) {
                trie_node->table[item - 'a'] = new trie_tree;
            }
            trie_node = trie_node->table[item - 'a'];
        }
        trie_node->end = true;
    }

    /** Returns if the word is in the trie. */
    bool search(string word) {
        trie_tree* trie_node = &trie_tree_head;
        for (char item : word) {
            if (trie_node->table[item - 'a'] == nullptr) {
                return false;
            }
            trie_node = trie_node->table[item - 'a'];
        }
        if (trie_node->end) {
            return true;
        }
        return false;
    }

    /** Returns if there is any word in the trie that starts with the given prefix. */
    bool startsWith(string prefix) {
        trie_tree* trie_node = &trie_tree_head;
        for (char item : prefix) {
            if (trie_node->table[item - 'a'] == nullptr) {
                return false;
            }
            trie_node = trie_node->table[item - 'a'];
        }
        return true;
    }
};

int main() {
    Trie trie;
    trie.insert("apple");
    trie.search("apple");   // 返回 true
    trie.search("app");     // 返回 false
    trie.startsWith("app"); // 返回 true
    trie.insert("app");
    trie.search("app");
    return 0;
}
